package com.kwdb.importtool.ui;

import com.kwdb.importtool.config.DatabaseConfig;
import com.kwdb.importtool.config.MigrationConfig;
import com.kwdb.importtool.core.KWDBMigrator;
import com.kwdb.importtool.model.MigrationResult;
import com.kwdb.importtool.util.LoggerUtil;
import lombok.Data;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 主窗口框架
 * 应用程序的主界面，集成所有功能组件
 */
public class MainFrame extends JFrame {
    private static final Logger logger = LoggerFactory.getLogger(MainFrame.class);

    // 核心组件
    private DragDropPanel dragDropPanel;
    private ConfigPanel configPanel;
    private JTabbedPane mainTabbedPane;

    // 菜单组件
    private JMenuBar menuBar;
    private JMenu fileMenu;
    private JMenu toolsMenu;
    private JMenu helpMenu;

    // 工具栏组件
    private JToolBar toolBar;

    // 状态栏组件
    private JPanel statusPanel;
    private JLabel statusLabel;
    private JProgressBar globalProgressBar;

    // 控制按钮
    private JButton startMigrationButton;
    private JButton stopMigrationButton;
    private JButton validateConfigButton;

    // 配置和数据
    private DatabaseConfig dbConfig;
    private MigrationConfig migrationConfig;
    private KWDBMigrator migrator;
    private boolean migrationInProgress;

    // 常量
    private static final String APP_TITLE = "MySQL to KWDB migrationTools";
    private static final String VERSION = "1.0.0";
    private static final Dimension WINDOW_SIZE = new Dimension(1000, 700);

    public MainFrame() {
        this.dbConfig = new DatabaseConfig();
        this.migrationConfig = new MigrationConfig();
        this.migrationInProgress = false;

        initializeFrame();
        initializeComponents();
        setupLayout();
        setupEventHandlers();
        applyLookAndFeel();

        logger.info("The main window is initialized");
    }

    /**
     * 初始化主窗口框架
     */
    private void initializeFrame() {
        setTitle(APP_TITLE + " v" + VERSION);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setSize(WINDOW_SIZE);
        setMinimumSize(new Dimension(800, 600));
        setLocationRelativeTo(null); // 居中显示

        // 设置应用程序图标
        setIconImage(createAppIcon());

        // 添加窗口关闭监听器
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                confirmExit();
            }
        });
    }

    /**
     * 初始化各个组件
     */
    private void initializeComponents() {
        // 创建拖拽面板
        dragDropPanel = new DragDropPanel();
        dragDropPanel.addFileDropListener(new DragDropPanel.FileDropListener() {
            @Override
            public void onFileDropped(File file) {
                handleFileDropped(file);
            }

            @Override
            public void onFileCleared() {
                handleFileCleared();
            }
        });

        // 创建配置面板
        configPanel = new ConfigPanel(dbConfig, migrationConfig);

        // 创建主选项卡面板
        mainTabbedPane = new JTabbedPane();
        mainTabbedPane.addTab("文件拖拽", createIcon("📁"), dragDropPanel, "拖拽SQL文件到此处");
        mainTabbedPane.addTab("配置设置", createIcon("⚙️"), configPanel, "配置数据库连接和迁移选项");

        // 创建菜单栏
        createMenuBar();

        // 创建工具栏
        createToolBar();

        // 创建状态栏
        createStatusBar();
    }

    /**
     * 设置布局
     */
    private void setupLayout() {
        setLayout(new BorderLayout());

        // 添加菜单栏
        setJMenuBar(menuBar);

        // 添加工具栏
        add(toolBar, BorderLayout.NORTH);

        // 添加主内容区域
        add(mainTabbedPane, BorderLayout.CENTER);

        // 添加状态栏
        add(statusPanel, BorderLayout.SOUTH);
    }

    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        // 选项卡切换事件
        mainTabbedPane.addChangeListener(e -> {
            int selectedIndex = mainTabbedPane.getSelectedIndex();
            if (selectedIndex == 0) {
                updateStatus("就绪：拖拽SQL文件开始迁移");
            } else if (selectedIndex == 1) {
                updateStatus("就绪：配置数据库连接和迁移选项");
            }
        });
    }

    /**
     * 创建菜单栏
     */
    private void createMenuBar() {
        menuBar = new JMenuBar();

        // 文件菜单
        fileMenu = new JMenu("文件");
        fileMenu.setMnemonic('F');

        JMenuItem openItem = new JMenuItem("打开SQL文件", createIcon("📂"));
        openItem.setMnemonic('O');
        openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
        openItem.addActionListener(e -> openSQLFile());

/*        JMenuItem configItem = new JMenuItem("加载配置", createIcon("⚙️"));
        configItem.setMnemonic('L');
        configItem.setAccelerator(KeyStroke.getKeyStroke("ctrl L"));
        configItem.addActionListener(e -> loadConfiguration());*/

        JMenuItem saveConfigItem = new JMenuItem("保存配置", createIcon("💾"));
        saveConfigItem.setMnemonic('S');
        saveConfigItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
        saveConfigItem.addActionListener(e -> saveConfiguration());

        JMenuItem exitItem = new JMenuItem("退出", createIcon("🚪"));
        exitItem.setMnemonic('X');
        exitItem.setAccelerator(KeyStroke.getKeyStroke("alt F4"));
        exitItem.addActionListener(e -> confirmExit());

        fileMenu.add(openItem);
        fileMenu.addSeparator();
//        fileMenu.add(configItem);
        fileMenu.add(saveConfigItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);

        // 工具菜单
        toolsMenu = new JMenu("工具");
        toolsMenu.setMnemonic('T');

        JMenuItem validateItem = new JMenuItem("验证配置", createIcon("✅"));
        validateItem.setMnemonic('V');
        validateItem.setAccelerator(KeyStroke.getKeyStroke("ctrl V"));
        validateItem.addActionListener(e -> validateConfiguration());

/*        JMenuItem testKwdbItem = new JMenuItem("测试KWDB连接", createIcon("🔗"));
        testKwdbItem.setMnemonic('K');
        testKwdbItem.addActionListener(e -> testKWDBConnection());*/

/*        JMenuItem testMysqlItem = new JMenuItem("测试MySQL连接", createIcon("🔗"));
        testMysqlItem.setMnemonic('M');
        testMysqlItem.addActionListener(e -> testMySQLConnection());*/

/*        JMenuItem migrationReportItem = new JMenuItem("生成迁移报告", createIcon("📊"));
        migrationReportItem.setMnemonic('R');
        migrationReportItem.setAccelerator(KeyStroke.getKeyStroke("ctrl R"));
        migrationReportItem.addActionListener(e -> generateMigrationReport());*/

        toolsMenu.add(validateItem);
        toolsMenu.addSeparator();
/*        toolsMenu.add(testKwdbItem);
        toolsMenu.add(testMysqlItem);*/
        toolsMenu.addSeparator();
//        toolsMenu.add(migrationReportItem);

        // 帮助菜单
        helpMenu = new JMenu("帮助");
        helpMenu.setMnemonic('H');

        JMenuItem aboutItem = new JMenuItem("关于", createIcon("ℹ️"));
        aboutItem.setMnemonic('A');
        aboutItem.setAccelerator(KeyStroke.getKeyStroke("F1"));
        aboutItem.addActionListener(e -> showAboutDialog());

        JMenuItem helpItem = new JMenuItem("使用帮助", createIcon("❓"));
        helpItem.setMnemonic('H');
        helpItem.setAccelerator(KeyStroke.getKeyStroke("F2"));
        helpItem.addActionListener(e -> showHelpDialog());

        helpMenu.add(helpItem);
        helpMenu.add(aboutItem);

        // 添加到菜单栏
        menuBar.add(fileMenu);
        menuBar.add(toolsMenu);
        menuBar.add(helpMenu);
    }

    /**
     * 创建工具栏
     */
    private void createToolBar() {
        toolBar = new JToolBar();
        toolBar.setFloatable(false);
        toolBar.setBorder(new EmptyBorder(5, 5, 5, 5));

        // 开始迁移按钮
        startMigrationButton = new JButton("开始迁移", createIcon("🚀"));
        startMigrationButton.setToolTipText("开始执行MySQL到KWDB的迁移");
        startMigrationButton.setEnabled(false);
        startMigrationButton.addActionListener(e -> startMigration());

        // 停止迁移按钮
        stopMigrationButton = new JButton("停止迁移", createIcon("⏹️"));
        stopMigrationButton.setToolTipText("停止当前迁移过程");
        stopMigrationButton.setEnabled(false);
        stopMigrationButton.addActionListener(e -> stopMigration());

        // 验证配置按钮
        validateConfigButton = new JButton("验证配置", createIcon("✅"));
        validateConfigButton.setToolTipText("验证当前配置的有效性");
        validateConfigButton.addActionListener(e -> validateConfiguration());

        // 添加分隔符和按钮
        toolBar.add(startMigrationButton);
        toolBar.add(stopMigrationButton);
        toolBar.addSeparator();
        toolBar.add(validateConfigButton);
        toolBar.addSeparator();

        // 添加灵活的空格
        toolBar.add(Box.createHorizontalGlue());

        // 添加快速操作按钮
/*        JButton settingsButton = new JButton("设置", createIcon("⚙️"));
        settingsButton.addActionListener(e -> showSettings());
        toolBar.add(settingsButton);*/
    }

    /**
     * 创建状态栏
     */
    private void createStatusBar() {
        statusPanel = new JPanel(new BorderLayout());
        statusPanel.setBorder(BorderFactory.createEtchedBorder());
        statusPanel.setPreferredSize(new Dimension(getWidth(), 23));

        // 状态标签
        statusLabel = new JLabel("就绪");
        statusLabel.setBorder(new EmptyBorder(0, 5, 0, 5));

        // 全局进度条
        globalProgressBar = new JProgressBar();
        globalProgressBar.setPreferredSize(new Dimension(200, 16));
        globalProgressBar.setVisible(false);

        statusPanel.add(statusLabel, BorderLayout.CENTER);
        statusPanel.add(globalProgressBar, BorderLayout.EAST);
    }

    /**
     * 应用外观和感觉
     */
    private void applyLookAndFeel() {
        try {
            // 使用系统外观 暂定
/*            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());
            SwingUtilities.updateComponentTreeUI(this);*/

            // 1. 获取系统默认外观的类名（此方法无异常）
            String systemLafClassName = UIManager.getSystemLookAndFeelClassName();
            // 2. 应用系统外观（此方法会抛出受检异常，必须捕获）
            UIManager.setLookAndFeel(systemLafClassName);
            // 3. 更新所有组件的外观，确保生效
            SwingUtilities.updateComponentTreeUI(this);
            logger.info("成功应用系统默认外观: {}", systemLafClassName);
        } catch (Exception e) {
            logger.warn("无法设置系统外观，使用默认外观");
        }
    }

    /**
     * 创建图标（使用文本表情符号作为简单图标）
     */
    private Icon createIcon(String emoji) {
        JLabel label = new JLabel(emoji);
        label.setFont(new Font("Segoe UI Emoji", Font.PLAIN, 16));
        return new Icon() {
            @Override
            public void paintIcon(Component c, Graphics g, int x, int y) {
                label.setSize(getIconWidth(), getIconHeight());
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.translate(x, y);
                label.paint(g2d);
                g2d.dispose();
            }

            @Override
            public int getIconWidth() {
                return 20;
            }

            @Override
            public int getIconHeight() {
                return 20;
            }
        };
    }

    /**
     * 创建应用程序图标
     */
    private Image createAppIcon() {
        // 创建一个简单的图标
        int size = 32;
        BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();

        // 设置抗锯齿
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 绘制数据库图标
        g2d.setColor(new Color(70, 130, 180)); // 钢蓝色
        g2d.fillRoundRect(4, 8, 24, 18, 5, 5);

        g2d.setColor(Color.WHITE);
        g2d.fillRect(8, 12, 16, 10);

        g2d.setColor(new Color(70, 130, 180));
        g2d.fillRect(10, 6, 12, 4);

        g2d.dispose();
        return image;
    }

    /**
     * 处理文件拖拽事件
     */
    private void handleFileDropped(File file) {
        migrationConfig.setSqlFilePath(file.getAbsolutePath());
        startMigrationButton.setEnabled(true);
        updateStatus("文件已加载: " + file.getName());

        // 切换到文件选项卡
        mainTabbedPane.setSelectedIndex(0);

        logger.info("文件加载成功: {}", file.getAbsolutePath());
    }

    /**
     * 处理文件清除事件
     */
    private void handleFileCleared() {
        migrationConfig.setSqlFilePath(null);
        startMigrationButton.setEnabled(false);
        updateStatus("就绪：拖拽SQL文件开始迁移");

        logger.info("文件已清除");
    }

    /**
     * 开始迁移过程
     */
    private void startMigration() {
        if (migrationInProgress) {
            showWarning("迁移正在进行中");
            return;
        }

        if (!configPanel.isConfigValid()) {
            showError("请先完成有效配置");
            return;
        }

        if (migrationConfig.getSqlFilePath() == null) {
            showError("请先选择SQL文件");
            return;
        }

        // 更新配置
        configPanel.updateConfigFromUI();

        // 开始迁移
        migrationInProgress = true;
        updateMigrationControls();

        // 在后台线程执行迁移
        new MigrationWorker().execute();
    }

    /**
     * 停止迁移过程
     */
    private void stopMigration() {
        if (!migrationInProgress) {
            return;
        }

        int result = JOptionPane.showConfirmDialog(this,
                "确定要停止当前迁移过程吗？",
                "确认停止",
                JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION) {
            if (migrator != null) {
                // 这里应该调用migrator的停止方法
                logger.info("用户请求停止迁移");
            }
            migrationInProgress = false;
            updateMigrationControls();
            updateStatus("迁移已停止");
        }
    }

    /**
     * 更新迁移控制按钮状态
     */
    private void updateMigrationControls() {
        startMigrationButton.setEnabled(!migrationInProgress && dragDropPanel.isFileLoaded());
        stopMigrationButton.setEnabled(migrationInProgress);
        validateConfigButton.setEnabled(!migrationInProgress);

        globalProgressBar.setVisible(migrationInProgress);
    }

    /**
     * 打开SQL文件
     */
    private void openSQLFile() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择MySQL SQL文件");
        fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.isDirectory() || file.getName().toLowerCase().endsWith(".sql");
            }

            @Override
            public String getDescription() {
                return "SQL文件 (*.sql)";
            }
        });

        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            dragDropPanel.handleDroppedFile(selectedFile);
        }
    }

    /**
     * 验证配置
     */
    private void validateConfiguration() {
        if (configPanel.validateConfig()) {
            showInfo("配置验证通过");
        }
    }

    /**
     * 测试KWDB连接
     */
    private void testKWDBConnection() {
        // 实现KWDB连接测试逻辑
        showInfo("KWDB连接测试功能待实现");
    }

    /**
     * 测试MySQL连接
     */
    private void testMySQLConnection() {
        // 实现MySQL连接测试逻辑
        showInfo("MySQL连接测试功能待实现");
    }

    /**
     * 加载配置
     */
    private void loadConfiguration() {
        // 实现配置加载逻辑
        showInfo("配置加载功能待实现");
    }

    /**
     * 保存配置
     */
    private void saveConfiguration() {
        // 实现配置保存逻辑
        showInfo("配置保存功能待实现");
    }

    /**
     * 生成迁移报告
     */
    private void generateMigrationReport() {
        // 实现报告生成逻辑
        showInfo("迁移报告生成功能待实现");
    }

    /**
     * 显示设置对话框
     */
    private void showSettings() {
        // 实现设置对话框
        showInfo("设置功能待实现");
    }

    /**
     * 显示关于对话框
     */
    private void showAboutDialog() {
        String aboutText = String.format(
                "<html>" +
                        "<head>" +
                        "<style>" +
                        "/* 基础样式 */" +
                        "body { margin: 0; padding: 0; font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif; }" +
                        ".container { width: 400px; padding: 25px; background-color: #f9fafb; border-radius: 8px; box-shadow: 0 3px 10px rgba(0,0,0,0.1); }" +

                        "/* 标题区域 */" +
                        ".header { text-align: center; margin-bottom: 20px; }" +
                        ".app-title { color: #1a56db; margin: 0; font-size: 22px; font-weight: 600; }" +
                        ".app-version { color: #64748b; margin: 8px 0 0; font-size: 14px; }" +

                        "/* 内容区域 */" +
                        ".content { margin: 15px 0; line-height: 1.8; }" +
                        ".desc-item { color: #334155; font-size: 14px; margin: 10px 0; }" +
                        ".feature { color: #0f766e; font-size: 14px; padding-left: 5px; }" +

                        "/* 分隔线 */" +
                        ".divider { height: 1px; background-color: #e2e8f0; margin: 18px 0; }" +

                        "/* 底部信息 */" +
                        ".footer { text-align: center; color: #64748b; font-size: 13px; padding-top: 10px; }" +
                        "</style>" +
                        "</head>" +
                        "<body>" +
                        "<div class='container'>" +
                        "<div class='header'>" +
                        "<h2 class='app-title'>%s</h2>" +
                        "<p class='app-version'>版本: %s</p>" +
                        "</div>" +

                        "<div class='content'>" +
                        "<p class='desc-item'>MySQL to KWDB 数据库迁移工具</p>" +
                        "<p class='feature'>✓ 支持MySQL SQL文件导入</p>" +
                        "<p class='feature'>✓ 适配KWDB数据库语法</p>" +
                        "<p class='feature'>✓ 批量迁移与日志记录</p>" +
                        "</div>" +

                        "<div class='divider'></div>" +

                        "<div class='footer'>" +
                        "开发团队: 舜云科技PLUS © 2024" +
                        "</div>" +
                        "</div>" +
                        "</body>" +
                        "</html>",
                APP_TITLE, VERSION
        );

        JOptionPane.showMessageDialog(this, aboutText, "关于", JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * 显示帮助对话框
     */
    private void showHelpDialog() {
        String helpText = String.format(
                "<html><div style='width: 400px;'>" +
                        "<h3>使用说明</h3>" +
                        "<ol>" +
                        "<li>将MySQL导出的SQL文件拖拽到文件拖拽区域</li>" +
                        "<li>在配置设置中配置KWDB数据库连接参数</li>" +
                        "<li>根据需要调整迁移选项</li>" +
                        "<li>点击'开始迁移'按钮执行迁移</li>" +
                        "</ol>" +
                        "<h3>支持的功能</h3>" +
                        "<ul>" +
                        "<li>CREATE DATABASE/TABLE语句</li>" +
                        "<li>INSERT数据导入</li>" +
                        "<li>索引和约束迁移</li>" +
                        "<li>数据类型自动转换</li>" +
                        "<li>迁移进度监控</li>" +
                        "</ul>" +
                        "</div></html>"
        );

        JOptionPane.showMessageDialog(this, helpText, "使用帮助", JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * 确认退出应用程序
     */
    private void confirmExit() {
        if (migrationInProgress) {
            int result = JOptionPane.showConfirmDialog(this,
                    "迁移正在进行中，确定要退出吗？",
                    "确认退出",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE);

            if (result != JOptionPane.YES_OPTION) {
                return;
            }
        }

        int result = JOptionPane.showConfirmDialog(this,
                "确定要退出应用程序吗？",
                "确认退出",
                JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION) {
            logger.info("应用程序退出");
            System.exit(0);
        }
    }

    /**
     * 更新状态栏
     */
    public void updateStatus(String message) {
        SwingUtilities.invokeLater(() -> {
            statusLabel.setText(message);
            statusLabel.setToolTipText(message);
        });
    }

    /**
     * 更新进度条
     */
    public void updateProgress(int progress, String message) {
        SwingUtilities.invokeLater(() -> {
            globalProgressBar.setValue(progress);
            globalProgressBar.setString(message);
            dragDropPanel.setProgress(progress, message);
        });
    }

    /**
     * 显示信息对话框
     */
    private void showInfo(String message) {
        JOptionPane.showMessageDialog(this, message, "信息", JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * 显示警告对话框
     */
    private void showWarning(String message) {
        JOptionPane.showMessageDialog(this, message, "警告", JOptionPane.WARNING_MESSAGE);
    }

    /**
     * 显示错误对话框
     */
    private void showError(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    /**
     * 迁移工作线程
     */
    private class MigrationWorker extends SwingWorker<MigrationResult, Integer> {
        @Override
        protected MigrationResult doInBackground() throws Exception {
            try {
                updateStatus("迁移进行中...");
                publish(0);

                String outputDir = migrationConfig.getOutputDir();
                if (outputDir != null && !outputDir.trim().isEmpty()) {
                    LoggerContext context = (LoggerContext) LogManager.getContext(false);
                    context.reconfigure(); // 强制重新加载配置
                }

                // 创建迁移器
                migrator = new KWDBMigrator(dbConfig, migrationConfig);

                // 设置进度监听器
                migrator.setProgressListener((message, progress) -> {
                    publish(progress);
                    updateStatus(message);
                });

                // 执行迁移
                MigrationResult result = migrator.executeMigration();
                publish(100);

                return result;

            } catch (Exception e) {
                logger.error("迁移过程出错", e);
                publish(-1);
                throw e;
            }
        }

        @Override
        protected void process(java.util.List<Integer> chunks) {
            if (!chunks.isEmpty()) {
                int progress = chunks.get(chunks.size() - 1);
                if (progress >= 0) {
                    updateProgress(progress, "迁移进度: " + progress + "%");
                }
            }
        }

        @Override
        protected void done() {
            migrationInProgress = false;
            updateMigrationControls();

            try {
                MigrationResult result = get();
                if (result.isSuccess()) {
                    updateStatus("迁移完成");
                    showInfo("迁移成功完成！\n处理语句: " + result.getTotalStatements() +
                            "\n成功: " + result.getSuccessfulStatements());
                } else {
                    updateStatus("迁移失败");
                    showError("迁移失败，详情见日志");
                }
            } catch (Exception e) {
                updateStatus("迁移出错");
                showError("迁移过程出错，详情见日志");
            }
        }
    }

    /**
     * 主方法 - 应用程序入口
     */
    public static void main(String[] args) {
        // 设置系统属性
        System.setProperty("awt.useSystemAAFontSettings", "on");
        System.setProperty("swing.aatext", "true");

        SwingUtilities.invokeLater(() -> {
            try {
                MainFrame mainFrame = new MainFrame();
                mainFrame.setVisible(true);

                LoggerUtil.info("应用程序启动成功");

            } catch (Exception e) {
                LoggerUtil.error("应用程序启动失败", e);
                JOptionPane.showMessageDialog(null,
                        "应用程序启动失败: " + e.getMessage(),
                        "启动错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        });
    }
}